package com.up.selfshop.util;

import java.io.File;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 * 发邮件
 * 
 * @author liuzy
 * @since 2015年10月20日
 */
public class EMail {
	public static void main(String[] args) {
		EMail.send("你瞅啥", "你瞅啥；瞅你咋滴；再瞅一个试试；试就试；……".replaceAll(";", ";\n"), new File[] { new File("c:/windows/notepad.exe") });
	}

	private static Executor executor = Executors.newFixedThreadPool(10);
	private static final String host = "smtp.163.com";
	private static final String user = "jinguozy@163.com";
	private static final String pass = "1qaz2wsx";
	private static final String to = "416657468@qq.com";

	public static void asyncSend(final String subject, final String content, final File[] files) {
		executor.execute(new Runnable() {
			@Override
			public void run() {
				EMail.send(subject, content, files);
			}
		});
	}

	public static boolean send(String subject, String content, File[] files) {
		try {
			Authenticator auth = new Authenticator() {
				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(user, pass);
				}
			};
			Properties props = new Properties();
			props.put("mail.smtp.host", host);
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.starttls.enable", "true");
			Session session = Session.getDefaultInstance(props, auth);
			MimeMessage message = new MimeMessage(session);
			message.setSubject(subject);
			message.setSentDate(new Date());
			Address from = new InternetAddress(user, user.substring(0, user.indexOf("@")));
			message.setFrom(from);
			Multipart mp = new MimeMultipart();
			MimeBodyPart tmbp = new MimeBodyPart();
			tmbp.setContent(content, "text/html;charset=utf8");
			mp.addBodyPart(tmbp);
			if (files != null && files.length > 0) {
				for (File file : files) {
					MimeBodyPart fmbp = new MimeBodyPart();
					FileDataSource fds = new FileDataSource(file);
					fmbp.setDataHandler(new DataHandler(fds));
					fmbp.setFileName(fds.getName());
					mp.addBodyPart(fmbp);
				}
			}
			message.setContent(mp);
			InternetAddress[] ddress = InternetAddress.parse(to);
			message.addRecipients(Message.RecipientType.TO, ddress);
			message.saveChanges();
			Transport.send(message);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

}
